<?php
namespace Admin\Controller;
class CategoryController extends AuthController{

    private $categoryModel;

    public function  _initialize()
    {
        $this->categoryModel= new \Admin\Model\CategoryModel();
        parent::_initialize();
    }

    //类表
    public function index(){
        //$this->categorys=$this->categoryModel->select();
       $this->categorys=$this->categoryModel->getTree();
       $this->display();
    }

    /*
     * 添加类
     * */
    public function add(){
        //$this->page_title='كاتىگورىيە قۇشۇش';
        $this->categorys=$this->categoryModel->getTree();
        $this->display();
    }

    /*
     *  处理表单发送的数据
     * */
    public  function  addhandler(){
        if(IS_POST){
            $post=I('post.');
           /* p($post);
            die();*/
          if(!$this->categoryModel->create($post))
          {
             $this->error($this->categoryModel->getError());
          }
          if(!$this->categoryModel->add($post)) $this->error('添加失败');
          $this->success('添加成功','index');
        }
    }
    /*
     * 删除操作*/
    public function delete()
    {
        $id = I('id', 0, 'intval');
        $pid = $this->categoryModel->where(array('id' => $id))->getField('pid');
        $this->categoryModel->where(array('pid' => $id))->save(array('pid' => $pid));
        if ($this->categoryModel->where(array('id' => $id))->delete()) {
            $data = ['status' => 1, 'message' => ' 删除成功'];
        } else {
            $data = ['status' => 0, 'message' => '  删除失败'];
        }
        $this->ajaxReturn($data);
    }

//    编辑分类
    public function edit($id){
        $this->page_title=" 编辑分类";
        //当前分类
        $this->categorys=$this->categoryModel->where(array('id'=>$id))->find();
        //所有分类
        //$this->category=$this->categoryModel->getTree();
        $this->category=$this->categoryModel->getNoMy($id);
//        p($this->category);
        //p($this->categorys['sort']);die();
        $this->display();
    }

    //处理编辑的数据
    public function saveHandler(){

          //p($_POST);die();
        if(!$this->categoryModel->save(I('post.')))  $this->error('编辑类失败');
        $this->success('编辑分类成功',U('Category/index'));
    }

    /*
     * 更该排序
     * */
     public  function changeSort(){
         //dump($_POST);die();
      if($this->categoryModel->where(array('id'=>I('post.id')))->save(array('sort'=>I('post.sort'))))
      {
          $data=['status'=>1,'message'=>' 排序成功'];
      }
      $this->ajaxReturn($data);
    }
 }